package com.mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.entity.MmallProduct;
import com.mall.entity.vo.ProductQuery;
import com.mall.service.MmallProductService;
import com.mall.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ppmall
 * @since 2021-09-19
 */
@CrossOrigin
@RestController
@RequestMapping("/mall/product")
public class MmallProductController {

    @Autowired
    private MmallProductService productService;

    @PostMapping("products/{cur}/{limit}")
    public R getProducts(@PathVariable("cur") long cur,
                         @PathVariable("limit") long limit,
                         @RequestBody ProductQuery productQuery){
        Page<MmallProduct> page = new Page<>(cur, limit);
        QueryWrapper<MmallProduct> wrapper = new QueryWrapper<>();

        Integer categoryId = productQuery.getCategoryId();
        String name = productQuery.getName();
        BigDecimal minPrice = productQuery.getMinPrice();
        BigDecimal maxPrice = productQuery.getMaxPrice();
        Integer status = productQuery.getStatus();

        if(categoryId != null) {
            wrapper.eq("category_id", categoryId);
        }

        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }

        if(minPrice != null) {
            wrapper.ge("price", minPrice);
        }

        if(maxPrice != null) {
            wrapper.le("price", maxPrice);
        }

        if(status != null) {
            wrapper.eq("status", status);
        }

        productService.page(page, wrapper);

        long total = page.getTotal();
        List<MmallProduct> records = page.getRecords();
        return R.ok().data("total", total).data("rows", records);
    }

    @GetMapping("/product")
    public R getProductById(Integer id) {
        MmallProduct product = productService.getProductById(id);
        return R.ok().data("product", product);
    }

    @PutMapping("/product")
    public R updateProductById(@RequestBody MmallProduct product) {
//        return productService.updateById(product) ? R.ok() : R.error();
        return productService.updateProductById(product) ? R.ok() : R.error();
    }

    @PostMapping("/product")
    public R addProduct(@RequestBody MmallProduct product) {
        return productService.saveProduct(product) ? R.ok() : R.error();
    }

    @DeleteMapping("/product/{id}")
    public R deleteProductById(@PathVariable("id") Integer id){
        return productService.removeProductById(id) ? R.ok() : R.error();
    }
}

